package org.lanqiao.api.admin;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.lanqiao.common.Constants;
import org.lanqiao.common.JsonResult;
import org.lanqiao.common.JsonResultWriter;



@WebServlet("/api/uploadk")
public class UploadImageServlet extends HttpServlet {
	/**
	 * 上传文件
	 */
	private static final long serialVersionUID = 1L;

	@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         String realPath ="F:\\img";	
        System.out.println("文件存放位置::"+realPath);
        String tempPath = "F:\\tempPath"; 
        System.out.println("临时文件存放位置:"+tempPath);
        File f = new File(realPath);
            if(!f.exists()&&!f.isDirectory()){
                System.out.println("目录或文件不存在! 创建目标目录。临时文件存放位置:");
                f.mkdir();
            }
        //判断临时目录是否存在（不存在则创建）
        File f1 = new File(tempPath);
            if(!f1.isDirectory()){
                System.out.println("临时文件目录不存在! 创建临时文件目录");
                f1.mkdir();
            }
        
            /**
              * 使用Apache文件上传组件处理文件上传步骤：
             * 
             * */
          //1、设置环境:创建一个DiskFileItemFactory工厂      
        DiskFileItemFactory factory = new DiskFileItemFactory();
        
      //设置上传文件的临时目录
        factory.setRepository(f1); 
        
      //2、核心操作类:创建一个文件上传解析器。
        ServletFileUpload upload = new ServletFileUpload(factory);
        //解决上传"文件名"的中文乱码//����ϴ�"�ļ���"����������
        upload.setHeaderEncoding("UTF-8");
        if(!ServletFileUpload.isMultipartContent(req)){
            System.out.println("不是上传文件，终止");
            return;
        }
       
            List<FileItem> items=null;
			try {
				items = upload.parseRequest(req);
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
			List<String>   uploadFiles =new ArrayList<String>();  
			if(items!=null && items.size()>0){
				   for(FileItem item:items){
		                if(item.isFormField()){  
		                    String filedName = item.getFieldName();
		                    String filedValue = item.getString("UTF-8");
		                    System.out.println("普通字段:"+filedName+"=="+filedValue);
		                }else{
		                          
		                    String fileName = item.getName();
		                  
		                    if(fileName==null||"".equals(fileName.trim())){  
		                        continue;
		                    }
		                    
		                    fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
		                    String filePath = realPath+"\\"+fileName;
		                    InputStream in = item.getInputStream();
		                    OutputStream out = new FileOutputStream(filePath);
		      
		                    byte b[] = new byte[1024];
		          
		                    int len = -1;
		                    
		                    while((len=in.read(b))!=-1){  
		                        out.write(b, 0, len);
		                    }
		                    out.close();
		                    in.close();
		                    item.delete();
		                    System.out.println("文件上传成功");
		                    uploadFiles.add(fileName);
		                }    
		            } 
			}
			JsonResult result=null;
			result=new JsonResult("添加成功",Constants.STATUS_SUCCESS,uploadFiles);
			JsonResultWriter.writer(resp, result);
    }
	
}
    
    